package dao.impl;

import dao.customerMapper;
import domain.CorderResult;
import domain.customer;
import domain.flower;
import utill.JDBCUtil;
import utill.ResultUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class customerMapperImpl implements customerMapper {
    /**
     * 通过顾客名称和密码查询该顾客
     * @param username
     * @param password
     * @return 顾客对象;
     */
    @Override
    public customer findByUsernameAndPassword(String username ,String password) {
        Connection connection = JDBCUtil.getConn();
        String sql="select * from customer where customerName=? and customerPasword=?";
        ResultSet rs=null;
        PreparedStatement  preparedStatement=null;
        List<customer> list=null;
        customer c =new customer();
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            rs=preparedStatement.executeQuery();
            list = ResultUtil.PackingCustomer(rs);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
             JDBCUtil.closeAll(preparedStatement,rs,connection);
        }
        return list.isEmpty() ? null : list.get(0) ;
    }

    /**
     * 通过顾客的Id查询顾客的订单;
     * @param id
     * @return 返回由CorderResult 包装过的订单数据
     */
    @Override
    public List<CorderResult> findOrders(Integer id) {
        ResultSet rs =null;
        List<CorderResult> corderResultList=null;
        PreparedStatement ps=null;
        Connection connection=null;

        try{
            connection=JDBCUtil.getConn();
            String sql="select f.storeName  , o.flowertype ,o.flowernumber,o.totalprice  ,o.orderdate from `order` o  JOIN flowerstore f on o.customerId=? and o.storeId=f.storeId";
            ps=connection.prepareStatement(sql);
            ps.setInt(1,id);
            rs=ps.executeQuery();
            corderResultList=ResultUtil.PackingCorderResult(rs);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
             JDBCUtil.closeAll(ps,rs,connection);
        }

        return corderResultList;
    }
}
